//
//  JSBaseTableViewController.m
//  NiubilityProject
//
//  Created by Apple on 2017/11/14.
//  Copyright © 2017年 Apple. All rights reserved.
//

#import "JSBaseTableViewController.h"

static char firstEntryKey;

@interface JSBaseTableViewController ()

@end

@implementation JSBaseTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.dataService = [[JSBaseDataService alloc] init];
    self.dataService.delegate = self;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (!objc_getAssociatedObject(self, &firstEntryKey)) {
        if ([self isShowLoadingState]) {
            [JSLoadingView showLoadingInView:self.view];
        }
        [self headerRefresh];
        objc_setAssociatedObject(self, &firstEntryKey, @(YES), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    
}
- (void)initTableView{
    [super initTableView];
    self.tableView.emptyDataSetSource = self;
    self.tableView.emptyDataSetDelegate = self;
//    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    self.tableView.mj_header = [CustomGifRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    // 自动改变透明度
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
//    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
    self.tableView.mj_footer = [CustomGifRefreshFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
    self.tableView.mj_footer.automaticallyChangeAlpha = YES;
    _isHidenHeaderRefresh = YES;
    _isHidenFooterRefresh = YES;
    [self.tableView.mj_footer endRefreshingWithNoMoreData];
    
}
- (void)headerRefresh{
//    self.page = 1;
//    [self.tableView.mj_footer endRefreshing];
//    self.params[@"page"] = @(self.page);
//    [self loadData:YES];
    [self.dataService refrenshData];
}
- (void)footerRefresh{
//    self.page ++;
//    self.params[@"page"] = @(self.page);
//    [self.tableView.mj_header endRefreshing];
//    [self loadData:NO];
    [self.dataService nextData];
}
//- (void)loadData:(BOOL)isNewData{
//    if (![self dataServiceUrlSting]) {
//        JSAlertWithMessge(@"方法名为空");
//        [self.tableView.mj_header endRefreshing];
//        [self.tableView.mj_footer endRefreshing];
//        return;
//    }
//    //    self.params[@"show"] = @(self.pageNumber);
//    JS_WeakSelf(self)
//    [JSNetManager js_courrentProjectRequestWithMouth:self.mouth cache:NO ifShowFinishStatu:NO parameters:self.params successBlock:^(id response) {
//        [weakself.tableView.mj_header endRefreshing];
//        [weakself.tableView.mj_footer endRefreshing];
//        NSString *status = response[@"status"];
//        if (isNewData) {
//            NSMutableArray *temp = weakself.dataSource;
//            [weakself.dataSource removeAllObjects];
//            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//                [temp class];
//            });
//        }
//        if (!self.requestDataHandle) return ;
//        if (status.integerValue == 100) {
//            self.requestDataHandle(response[@"data"], nil);
//        }else{
//            self.requestDataHandle(nil, [NSError errorWithDomain:NSCocoaErrorDomain code:status.integerValue userInfo:@{@"decription":response[@"msg"]}]);
//        }
//
//    } failureBlock:^(NSError *error) {
//        [weakself.tableView.mj_header endRefreshing];
//        [weakself.tableView.mj_footer endRefreshing];
//        if (!isNewData) {
//            weakself.page --;
//        }
//    }];
//
//}
- (void)setIsHidenFooterRefresh:(BOOL)isHidenFooterRefresh{
    _isHidenFooterRefresh = isHidenFooterRefresh;
    if (isHidenFooterRefresh) {
        self.tableView.mj_footer = nil;
    }else{
        self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
        self.tableView.mj_footer.automaticallyChangeAlpha = YES;
    }
}
- (void)setIsHidenHeaderRefresh:(BOOL)isHidenHeaderRefresh{
    _isHidenHeaderRefresh = isHidenHeaderRefresh;
    if (_isHidenHeaderRefresh) {
        self.tableView.mj_header = nil;
    }else{
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
        // 自动改变透明度
        self.tableView.mj_header.automaticallyChangeAlpha = YES;
    }
}
- (void)footerRefreshType{
    if (self.dataSource.count < self.dataService.page * 10) {
        [self.tableView.mj_footer resetNoMoreData];
    }else{
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }
}

#pragma mark - DZNEmptyDataSetSource
// 空白页图片
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView{
    return [UIImage imageNamed:@"noData"];
}
// 标题文本，富文本样式
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *text = @"暂无数据";
    NSDictionary *attributes = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:14.0f],
                                 NSForegroundColorAttributeName: JS_ColorWithRGB(222, 222, 222)};
    
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
}


// 是否 允许上下滚动，默认NO
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    return YES;
}
//设置当前导航栏是否需要使用自定义的 push 时候 transition 效果，默认返回NO，须足这里配置设置YES。
- (BOOL)shouldCustomNavigationBarTransitionWhenPushAppearing {
    return YES;
}
//设置当前导航栏是否需要使用自定义的 pop  时候 transition 效果，默认返回NO，须足这里配置设置YES。
- (BOOL)shouldCustomNavigationBarTransitionWhenPopAppearing {
    return YES;
}

//- (NSMutableDictionary *)params{
//    if (!_params) {
//        _params = @{}.mutableCopy;
//    }
//    return _params;
//}
//MARK:懒加载
-(NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = @[].mutableCopy;
    }
    return _dataSource;
}
#pragma mark -------JSDataServiceDelegate-----------------
// 请求数据回调
-(void)dataServiceDidUpdate:(JSBaseDataService *)service data:(id)data error:(NSError *)error{
    NSLog(@"data:%@ -- error:%@", data,error);
    [JSLoadingView hidenLoadingForView:self.view];
//    [self footerRefreshType];
}
-(NSString *)dataServiceUrlSting{
    // 请求所需url
    return BASE_URL;
}
-(NSMutableDictionary *)dataServiceParameter{
    // 请求所需参数
    return @{}.mutableCopy;
}
// 结束下拉刷新
-(void)overHeaderRefrensh{
    [self.tableView.mj_header endRefreshing];
}
/*!
 结束上拉加载更多
 
 isResstingData : 是否重置数据
 */
-(void)overFooterRefrensh:(BOOL)isResstingData{
    if (isResstingData) {
        NSMutableArray *temp = self.dataSource;
        [self.dataSource removeAllObjects];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [temp class];
        });
    }
    [self.tableView.mj_footer endRefreshing];
}
-(NSInteger)dataServicePageNumber{
    return 0;
}
- (void)dealloc{
    JSLog(@"%s",__func__);
}
#pragma mark - ***** 解决tableview的分割线短一截
- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]){
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]){
        [self.tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]){
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([self isExecuteCellAnimation]) {
        
    /*! 第一种：3d xyz三维坐标刚出现0.1 0.1 1  0.5 s后正常 */
    //    cell.layer.transform = CATransform3DMakeScale(0.1,0.1,1);
    //    [UIView animateWithDuration:0.6 animations:^{
    //
    //        cell.layer.transform = CATransform3DMakeScale(1,1,1);
    //
    //    }];
    
    /*! 第二种：卡片式动画 */
    static CGFloat initialDelay = 0.2f;
    static CGFloat stutter = 0.06f;
    
    cell.contentView.transform =  CGAffineTransformMakeTranslation(SCREEN_WIDTH, 0);
    
    [UIView animateWithDuration:1.0f delay:initialDelay + ((indexPath.row) * stutter) usingSpringWithDamping:0.6 initialSpringVelocity:0 options:0 animations:^{
        cell.contentView.transform = CGAffineTransformIdentity;
    } completion:NULL];
    
    /*! 第三种：从下往上 */
    
    //    [UIView animateWithDuration:1 animations:^{
    //
    //        cell.layer.transform = CATransform3DMakeTranslation(0, 0, 0);
    //
    //    }];
    
    /*! 第四种：右下角出来 */
    
    //    cell.layer.transform = CATransform3DMakeTranslation(SCREEN_WIDTH, SCREEN_HEIGHT, 0);
    //
    //    [UIView animateWithDuration:0.5 animations:^{
    //
    //        cell.layer.transform = CATransform3DMakeTranslation(0, 0, 0);
    //
    //    }];
    
    /*! 第五种：右上角出现 */
    
    //    cell.layer.transform = CATransform3DMakeTranslation(SCREEN_WIDTH, -SCREEN_HEIGHT, 0);
    
    /*! 第六种：翻转动画 */
    //    CATransform3D rotation;
    //    rotation = CATransform3DMakeRotation( (90.0*M_PI)/180, 0.0, 0.7, 0.4);
    //    rotation.m44 = 1.0/ -600;
    //    //阴影
    //    cell.layer.shadowColor = [[UIColor blackColor]CGColor];
    //
    //    //阴影偏移
    //    cell.layer.shadowOffset = CGSizeMake(10, 10);
    //    cell.alpha = 0;
    //    cell.layer.transform = rotation;
    //    //锚点
    //    cell.layer.anchorPoint = CGPointMake(0.5, 0.5);
    //    [UIView beginAnimations:@"rotation" context:NULL];
    //    [UIView setAnimationDuration:0.8];
    //    cell.layer.transform = CATransform3DIdentity;
    //    cell.alpha = 1;
    //    cell.layer.shadowOffset = CGSizeMake(0, 0);
    //    [UIView commitAnimations];
    
    /*! 第七种：扇形动画 */
    //    NSArray *array = tableView.indexPathsForVisibleRows;
    //
    //    NSIndexPath *firstIndexPath = array[0];
    //    //设置anchorPoint﻿
    //    cell.layer.anchorPoint = CGPointMake(0, 0.5);
    //
    //    //为了防止cell视图移动，重新把cell放回原来的位置﻿
    //    cell.layer.position = CGPointMake(0, cell.layer.position.y);
    //     //设置cell 按照z轴旋转90度，注意是弧度﻿
    //    if (firstIndexPath.row < indexPath.row)
    //    {
    //        cell.layer.transform = CATransform3DMakeRotation(M_PI_2, 0, 0, 1.0);
    //    }
    //    else
    //    {
    //        cell.layer.transform = CATransform3DMakeRotation(- M_PI_2, 0, 0, 1.0);
    //    }
    //    cell.alpha = 0.0;
    //    [UIView animateWithDuration:1 animations:^{
    //
    //        cell.layer.transform = CATransform3DIdentity;
    //
    //        cell.alpha = 1.0;
    //
    //    }];
    }

}

- (void)showMessage:(NSString *)msg {
    CGFloat padding = 10;
    
    YYLabel *label = [YYLabel new];
    label.text = msg;
    label.font = [UIFont systemFontOfSize:16];
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor whiteColor];
    label.backgroundColor = [UIColor colorWithRed:0.033 green:0.685 blue:0.978 alpha:0.730];
    label.width = self.view.width;
    label.textContainerInset = UIEdgeInsetsMake(padding, padding, padding, padding);
    label.height = [msg heightForFont:label.font width:label.width] + 2 * padding;
    
    label.bottom = (kiOS7Later ? 64 : 0);
    [self.view addSubview:label];
    [UIView animateWithDuration:0.3 animations:^{
        label.top = (kiOS7Later ? 64 : 0);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.2 delay:2 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            label.bottom = (kiOS7Later ? 64 : 0);
        } completion:^(BOOL finished) {
            [label removeFromSuperview];
        }];
    }];
}

-(BOOL)isShowLoadingState{
    return NO;
}

-(BOOL)isExecuteCellAnimation{
    return NO;
}
@end
